// const api_url = 'https://pre-henanopera.hndt.com/opera'
const api_url = 'https://henanopera.hndt.com/opera'
// const api_url = 'http://10.8.53.18:62316/opera'
const token = wx.getStorageSync('token')

// 例外不用token的地址
var exceptionAddrArr = ['/user/userLogin'];

//请求头处理函数
const createHeader = (url, type) =>  {
  let header = {}
  if (type == 'POST_PARAMS') {
      header = {
          'content-type': 'application/x-www-form-urlencoded'
      }
  } else {
      header = {
          'content-type': 'application/json'
      }
  }
  if (exceptionAddrArr.indexOf(url) == -1) { //排除请求的地址不须要token的地址
      let token = wx.getStorageSync('token') || '';
      if (token) header['token'] = 'Bearer:' + token;
  }
  return header;
}

/**
 * 请求拦截器:
 * 在这里实现的作用是将所有请求前判断用户是否授权获取用户信息
 * @param {*} config 
 */
const requestInterceptor = async (config) =>  {
  console.log("经过请求拦截器")
  return new Promise((resolve, reject) => {
    console.log(config,'resolve')
      if (!config.header.token) {
          userLogin().then(res =>{
              if(res){
                  let token = wx.getStorageSync('token') || '';
                  console.log(token,'token')
                  if(token) config.header.token = 'Bearer:' + token;
                  resolve(config);
              }
          })
      } else {
          resolve(config);
      }
  });
}


// 响应拦截器
const responseInterceptor = (response) => {
  console.log("经过响应拦截器")
  console.log(response)
  return new Promise((resolve, reject) => {
      // 处理响应结果
      if (response.data.code === 401) {
        userLogin().then(res => {
            reject(response)
        })
    } else {
      resolve(response);
    }
  });
}

/**
 * wx.login
 */
const wxLogin = async () => {
  console.log('jinlaile')
  try {
    const res = await wx.login();
    console.log(res,'wwww')
    return Promise.resolve(res.code);
  } catch (error) {
    console.log(error,'wwww')
    return Promise.reject(error);
  }
}

// code换取token
const userLogin = async () => {
  let code = await wxLogin();
  return new Promise((resolve, reject) => {
    wx.request({
      url: api_url + '/user/userLogin',
      data: { jsCode: code },
      method: 'get',
      success: (res => {
        console.log(res,'code')
        wx.setStorageSync('token', res.data.data)
        return resolve(true)
      }),
      fail: (res => {
        return resolve(false)
      }),
    })
  })
}



export default{
  get(url, data){
    let header = createHeader(url, 'GET');
    return new Promise((resolve, reject)=>{
      const config = {
        url: api_url + url,
        method: 'GET',
        data,
        header: header,
        success(res) {
          responseInterceptor(res).then(response => {
            console.log(response,'response')
            resolve(response.data);
        }).catch(res => {})
        },
        error(err){
          reject(err)
        }
      }
       // 请求拦截器
       requestInterceptor(config)
       .then(config => {
           wx.request(config);
       }).catch(error => {
           reject(error);
       });
    })
  },
  post(url, data) {
    let header = createHeader(url, 'GET');
    return new Promise((resolve, reject) => {
      const config = {
        url: api_url + url,
        method: 'POST',
        data,
        header: header,
        success(res) {
          resolve(res.data)
        },
        error(err) {
          reject(err)
        }
      }
       // 请求拦截器
       requestInterceptor(config)
       .then(config => {
           wx.request(config);
       }).catch(error => {
           reject(error);
       });
    })
  },
  upload(url, data) {
    let header = createHeader(url, 'GET');
    return new Promise((resolve, reject) => {
      const config = {
        url: api_url + url,
        method: 'POST',
        name: 'file',
        filePath: data,
        header: header,
        success(res) {
          resolve(res.data)
        },
        error(err) {
          reject(err)
        }
      }
       // 请求拦截器
       requestInterceptor(config)
       .then(config => {
           wx.uploadFile(config);
       }).catch(error => {
           reject(error);
       });
    })
  }
}